//
//  PicturePickerController.swift
//  阳光图片选择
//
//  Created by 阿拉斯加的狗 on 15/12/17.
//  Copyright © 2015年 阿拉斯加的🐶. All rights reserved.
//

import UIKit

/// 可重用 cell
private let PicturePickerCellId = "PicturePickerCellId"
/// 最大选择照片数量
private let PicturePickerMaxCount = 3

class PicturePickerController: UICollectionViewController {

    //配图数组
    lazy var pictures = [UIImage]()
    
    //用户选择照片索引
    private var selestedIndex = 0
    
    //MARK: - 构造函数
    init() {
    
        super.init(collectionViewLayout: PickurePickerLayout())
    
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        collectionView?.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
        
        self.collectionView!.registerClass(PicturePickerCell.self, forCellWithReuseIdentifier: PicturePickerCellId)


    }

    
    //MARK: - 照片选择器布局
    private class PickurePickerLayout: UICollectionViewFlowLayout {
    
        private override func prepareLayout() {
            
            super.prepareLayout()
            
            let count: CGFloat = 4
            let margin = UIScreen.mainScreen().scale * 4
            let w = (collectionView!.bounds.width - (count + 1) * margin) / 4
            
            itemSize = CGSize(width: w, height: w)
            minimumLineSpacing = margin
            minimumInteritemSpacing = margin
            sectionInset = UIEdgeInsets(top: margin, left: margin, bottom: 0, right: margin)

        }
    }
   
}


extension PicturePickerController {

    
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        return pictures.count + (pictures.count == PicturePickerMaxCount ? 0 : 1)
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PicturePickerCellId, forIndexPath: indexPath) as! PicturePickerCell
        
        cell.image = (indexPath.item < pictures.count) ? pictures[indexPath.item] : nil
        
        cell.pictureDelegate = self
        
        return cell
    }

}

//遵守协议
extension PicturePickerController: PicturePickerCellDelegate {

   @objc private func picturePickerCellDidAdd(cell: PicturePickerCell) {
    
    //访问授权
    if !UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary){
    
        print("无法访问照片库")
        return
    }
    
    //记录当前用户选中的照片索引
    selestedIndex = collectionView?.indexPathForCell(cell)?.item ?? 0
    
    let picker = UIImagePickerController()
    
    //设置代理
    picker.delegate = self
    
    presentViewController(picker, animated: true, completion: nil)
    
    
    }
    
   @objc private func picturePickerCellDidRemove(cell: PicturePickerCell) {
    
        //1.获取索引
    let indexPath = collectionView!.indexPathForCell(cell)!
    
        //判断索引是否超出上限
    if indexPath.item >= pictures.count {
    
        return
    }
    
    pictures.removeAtIndex(indexPath.item)
    
    //刷新数据
//    collectionView?.deleteItemsAtIndexPaths([indexPath])
    //刷新数据
    collectionView?.reloadData()
    
    
    }
}

/// UIImagePickerControllerDelegate, UINavigationControllerDelegate
extension PicturePickerController: UIImagePickerControllerDelegate,UINavigationControllerDelegate{

    //照片选择完成
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        
        //获取图片添加到数组中
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        
        let scaleImage = image.scaleToWith(600)
        
        if selestedIndex >= pictures.count {
        
            pictures.append(scaleImage)
            
        }else {
        
            pictures[selestedIndex] = scaleImage
        }
        
        
        //刷新视图
        collectionView?.reloadData()
        
        //销毁控制器选择完成后
        dismissViewControllerAnimated(true, completion: nil)
        
    }

}


//定义一个协议
@objc
private protocol PicturePickerCellDelegate:NSObjectProtocol {

    //添加照片
    optional func picturePickerCellDidAdd(cell: PicturePickerCell)
    
    //删除照片
    optional func picturePickerCellDidRemove(cell: PicturePickerCell)

}


/// 自定义cell
private class PicturePickerCell: UICollectionViewCell {

    //定义一个代理
    weak var pictureDelegate: PicturePickerCellDelegate?
    
    //设置图片属性
    var image: UIImage? {
    
        didSet{
            
            addButton.setImage(image ?? UIImage(named: "compose_pic_add"), forState: .Normal)
        
            //隐藏删除按钮
            removeButton.hidden = (image == nil)
        }
        
    }
    
    //监听方法
    @objc func addPicture() {
  
        pictureDelegate?.picturePickerCellDidAdd?(self)
    
    }
    
    @objc func removePicture() {
   
        pictureDelegate?.picturePickerCellDidRemove?(self)
        
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setUpUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    //设置控件
    private func setUpUI() {
    
        //添加控件
        contentView.addSubview(addButton)
        contentView.addSubview(removeButton)
        
        //设置布局
        addButton.frame = bounds
        
        removeButton.snp_makeConstraints { (make) -> Void in
            
            make.top.equalTo(contentView.snp_top)
            make.right.equalTo(contentView.snp_right)
            
        }
    
        //监听方法
        addButton.addTarget(self, action: "addPicture", forControlEvents: .TouchUpInside)
        removeButton.addTarget(self, action: "removePicture", forControlEvents: .TouchUpInside)
        
        //设置图片填充模式
        addButton.imageView?.contentMode = .ScaleAspectFill
    
    }
    
    //懒加载控件
    private lazy var addButton: UIButton = UIButton(imageName: "compose_pic_add", backImageName: nil)
    
    private lazy var removeButton: UIButton = UIButton(imageName: "compose_photo_close", backImageName: nil)

}

